package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import com.sun.xml.internal.bind.v2.TODO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IFollowService followService;
    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("博客不存在");
        }
        //查询blog有关的用户
        queryBlogUser(blog);
        //查询blog是否点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user== null){
            //用户未登录不用查询
            return;
        }
        //查看当前用户
        Long userId =user.getId();
        //查询redis
        String key = BLOG_LIKED_KEY + blog.getId();
        //根据查询score来判断此用户有没有点过赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null){
            //如果点赞，则设置isLike为true
            blog.setIsLike(true);
        }
    }

    //分页查询
    @Override
    public Result queryHotBlog(Integer current) {
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        //获取当前页数据
        List<Blog> records = page.getRecords();
        //查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    //点赞列表
    @Override
    public Result queryBlogLikes(Long id) {
        //查询top5点赞用户
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //解析用户id
        if (top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        //根据用户id查询用户
        List<User> users = userService.query().in("id",ids).last("order by field(id,"+idStr+")").list();
        //转为UserDTO
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("新增笔记失败");
        }
        //查询用户粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        if (follows == null || follows.isEmpty()){
            //无粉丝，无需推送
            return Result.ok();
        }
        //解析粉丝id
        List<Long> userIds = follows.stream().map(Follow::getUserId).collect(Collectors.toList());
        //推送消息
        userIds.forEach(userId -> {
            //推送
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        });
        return Result.ok(blog.getId());
    }

    //实现滚动分页查询关注的blog
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //获取当前用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //查询收信箱
        String key = FEED_KEY + userId;
        //获取收信箱中的blogId
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()){
            //没有数据
            return Result.ok();
        }
        //解析数据：blogId minTime offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //blogId
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if (time == minTime){
                os++;
            }else {
                //minTime
                minTime = time;
                os = 1;
            }

        }
        //根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Blog blog : blogList) {
            //博客作者信息
            queryBlogUser(blog);
            //点赞信息
            isBlogLiked(blog);
        }
        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
}

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    //集群模式一个人只能对同一博客点赞一次
    public Result likeBlog1(Long id) throws InterruptedException {
        //查看当前用户
        Long userId = UserHolder.getUser().getId();
        //查询redis
        String key = BLOG_LIKED_KEY + id;
        RLock lock = redissonClient.getLock("lock:blog:"+id);
        boolean isLock = lock.tryLock(1, TimeUnit.SECONDS);
        try {
            if (!isLock){
                return Result.fail("请勿重复点赞");
            }
            //根据查询score来判断此用户有没有点过赞
            Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
            //判断是否已经点赞
            //如果未点赞，可以点赞
            if (score == null){
                // TODO: 2025/5/4 由于数据库和redis是分步完成的，可能造成线程安全问题，多赞或者多删除赞，单体项目对用户id加锁就可，集群项目需要使用分布式锁
                //修改数据库
                boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
                //修改redis
                if (isSuccess){
                    //sortedSet中的score是时间戳,可以根据时间戳排序，以此返回点赞人列表，先点赞的在前
                    stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
                }
            }else {
                //如果已经点赞，取消点赞
                boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
                if (isSuccess){
                     stringRedisTemplate.opsForZSet().remove(key, userId.toString());
                }
            }
        } finally {
            if (isLock){
                lock.unlock();
            }
        }
        return Result.ok();
    }

    //单体项目下一人对同一博客只能点赞一次
    @Override
    public Result likeBlog(Long id) throws InterruptedException {
        //查看当前用户
        Long userId = UserHolder.getUser().getId();
        //查询redis
        String key = BLOG_LIKED_KEY + id;
        //根据查询score来判断此用户有没有点过赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //判断是否已经点赞
        //如果未点赞，可以点赞
        synchronized (userId.toString().intern()) {
            if (score == null) {
                // TODO: 2025/5/4 由于数据库和redis是分步完成的，可能造成线程安全问题，多赞或者多删除赞，单体项目对用户id加锁就可，集群项目需要使用分布式锁
                //修改数据库
                boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
                //修改redis
                if (isSuccess) {
                    //sortedSet中的score是时间戳,可以根据时间戳排序，以此返回点赞人列表，先点赞的在前
                    stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
                }
            } else {
                //如果已经点赞，取消点赞
                boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
                if (isSuccess) {
                    stringRedisTemplate.opsForZSet().remove(key, userId.toString());
                }
            }
        }
        return Result.ok();
    }
}
